class Podcast < ActiveRecord::Base
  attr_accessor :owners;
  
  has_many :episodes;
  has_many :memberships;
  has_many :users, :through => :memberships;
  has_many :taggings, :as => :taggable;
  has_many :tags, :through => :taggings;
  
  validates_presence_of :title, :description;
  validates_size_of :title, :within => 1..50;
  validates_size_of :description, :within => 1..1024;
  validate :must_have_owner;
  
  before_save :make_owners;
  
  class UserNotAllowed < StandardError; end
  
  def user_type(user)
    (user?(user)) ? (owner?(user)) ? :owner : :member : nil;
  end
  
  def user?(user)
    users.include?(user);
  end
  
  def owner?(user)
    owners.include?(user);
  end
  
  def member?(user)
    user?(user) and not owner?(user);
  end
  
  def owners
    @owners ||= memberships.select(&:owner).map(&:user);
  end
  
  def change_user_type(user, type)
    raise UserNotAllowed unless user?(user);
    case type
      when :owner then @owners << user;
      when :member then @owners.delete(user);
    end
  end
  
  protected
  def make_owners
    raise UserNotAllowed unless @owners.all?{|user| user?(user);};
    memberships.each do |membership|
      membership.owner = @owners.include?(membership.user);
      membership.save;
    end
  end
  
  def must_have_owner
    errors.add_to_base("Podcast must have at least one owner") if owners.empty?;
  end
  
end